package com.woniuxy.kaer.tenants.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.kaer.commons.util.Data;
import com.woniuxy.kaer.commons.util.OSSUtil;
import com.woniuxy.kaer.redis.util.RedisKey;
import com.woniuxy.kaer.tenants.dto.SettleApplyDto;
import com.woniuxy.kaer.tenants.entity.ApplyAttachments;
import com.woniuxy.kaer.tenants.entity.Founder;
import com.woniuxy.kaer.tenants.entity.Settled;
import com.woniuxy.kaer.tenants.mapper.ApplyAttachmentsMapper;
import com.woniuxy.kaer.tenants.mapper.FounderMapper;
import com.woniuxy.kaer.tenants.mapper.SettledMapper;
import com.woniuxy.kaer.tenants.param.TenantsApplyAuditParam;
import com.woniuxy.kaer.tenants.param.TenantsApplyParam;
import com.woniuxy.kaer.tenants.service.SettledService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 程诗洋
 * @since 2025年02月17日
 */
@Service
public class SettledServiceImpl extends ServiceImpl<SettledMapper, Settled> implements SettledService {
    @Resource
    private FounderMapper founderMapper;
    @Resource
    private SettledMapper settledMapper;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private OSSUtil ossUtil;
    @Resource
    private ApplyAttachmentsMapper applyAttachmentsMapper;
    @Override
    public void settledApply(TenantsApplyParam param) throws Exception {
        System.out.println("*"+param.getAttachmentUrl()+"*");
        byte[] bytes = new byte[4];
        param.getAttachmentUrl().getInputStream().read(bytes);
        if(!ossUtil.isPdf(bytes)){
            throw new Exception("文件格式不正确");
        }
        QueryWrapper<Founder> founderQueryWrapper = new QueryWrapper<>();
        Founder founder = founderMapper.selectById(param.getFounderId());
        if(null==founder){
            throw new Exception("商铺不存在");
        }
        if(founder.getFounderState()== Data.FOUNDER_STATE_DISABLE||founder.getFounderState()== Data.FOUNDER_STATE_DELETE){
            throw new Exception("商铺状态异常");
        }
        RLock lock = redissonClient.getFairLock(RedisKey.Lock_SETTLED_APPLY_BUSS(param.getSettledMobile()) + "settledApply");
        lock.lock();
        try {
            Settled settled = BeanUtil.toBean(param, Settled.class);
            settled.setCommitTime(LocalDateTime.now());
            settled.setSettledState(Data.SETTLED_STATE_NORMAL);
            settledMapper.insert(settled);
            Integer settledId = settled.getSettledId();
            String s = FileUtil.extName(param.getAttachmentUrl().getOriginalFilename());
            String s1 = UUID.randomUUID().toString();
            String AttachmentUrl = ossUtil.uploadFile(param.getAttachmentUrl().getInputStream(), s1 + "." + s, "guojiandong");
            ApplyAttachments applyAttachments = BeanUtil.toBean(param, ApplyAttachments.class);
            applyAttachments.setAttachmentUrl(AttachmentUrl);
            applyAttachments.setSettledId(settledId);
            //服务器地址填写的是oss存储空间名
            applyAttachments.setServiceName("guojiandong");
            applyAttachmentsMapper.insert(applyAttachments);
        }finally {
            lock.unlock();
        }

    }

    @Override
    public void settledApplyAudit(TenantsApplyAuditParam param) throws Exception {
        Settled settled = settledMapper.selectById(param.getSettledId());
        if(null==settled){
            throw new Exception("申请记录不存在");
        }
        if(settled.getSettledState()!=Data.SETTLED_STATE_NORMAL){
            throw new Exception("申请记录状态异常");
        }
        settled.setAuditTime(LocalDateTime.now());
        settled.setSettledState(param.getSettledState());
        settled.setRefundReason(param.getRefundReason());
        settled.setReviewer(param.getReviewer());
        settledMapper.updateById(settled);
    }

    @Override
    public List<SettleApplyDto> getSettledApply(Integer founderId) throws Exception {
        QueryWrapper<Settled> settledQueryWrapper = new QueryWrapper<>();
        settledQueryWrapper.eq("founder_id",founderId);
        List<Settled> settleds = settledMapper.selectList(settledQueryWrapper);
        if(settleds.size()==0){
            throw new Exception("申请记录不存在");
        }
        ArrayList<SettleApplyDto> settleApplyDtos = new ArrayList<>();
        for (Settled settled : settleds) {
            QueryWrapper<ApplyAttachments> applyAttachmentsQueryWrapper = new QueryWrapper<>();
            applyAttachmentsQueryWrapper.eq("settled_id",settled.getSettledId());
            ApplyAttachments applyAttachments = applyAttachmentsMapper.selectOne(applyAttachmentsQueryWrapper);
            if(null==applyAttachments){
                throw new Exception("申请附件不存在");
            }
            SettleApplyDto settleApplyDto = BeanUtil.toBean(settled, SettleApplyDto.class);
            settleApplyDto.setAttachmentName(applyAttachments.getAttachmentName());
            settleApplyDto.setAttachmentUrl(applyAttachments.getAttachmentUrl());
            settleApplyDto.setServiceName(applyAttachments.getServiceName());
            settleApplyDto.setAttachmentsId(applyAttachments.getAttachmentsId());
            settleApplyDtos.add(settleApplyDto);
        }
//        QueryWrapper<ApplyAttachments> applyAttachmentsQueryWrapper = new QueryWrapper<>();
//        applyAttachmentsQueryWrapper.eq("settled_id",settled.getSettledId());
//        ApplyAttachments applyAttachments = applyAttachmentsMapper.selectOne(applyAttachmentsQueryWrapper);
//        if(null==applyAttachments){
//            throw new Exception("申请附件不存在");
//        }
//        SettleApplyDto settleApplyDto = BeanUtil.toBean(settled, SettleApplyDto.class);
//        settleApplyDto.setAttachmentName(applyAttachments.getAttachmentName());
//        settleApplyDto.setAttachmentUrl(applyAttachments.getAttachmentUrl());
//        settleApplyDto.setServiceName(applyAttachments.getServiceName());
//        settleApplyDto.setAttachmentsId(applyAttachments.getAttachmentsId());
        return settleApplyDtos;
    }

    @Override
    public void refuseSettledApply(TenantsApplyAuditParam param) throws Exception {

    }

    @Override
    public List<SettleApplyDto> getSettledApplyByManager() throws Exception {
        QueryWrapper<Settled> settledQueryWrapper = new QueryWrapper<>();
        settledQueryWrapper.eq("settled_state",Data.SETTLED_STATE_NORMAL);
        ArrayList<SettleApplyDto> settleApplyDtos = new ArrayList<>();
        List<Settled> settleds = settledMapper.selectList(settledQueryWrapper);
        for (Settled settled : settleds) {
            SettleApplyDto settleApplyDto = BeanUtil.toBean(settled, SettleApplyDto.class);
            QueryWrapper<ApplyAttachments> applyAttachmentsQueryWrapper = new QueryWrapper<>();
            applyAttachmentsQueryWrapper.eq("settled_id",settled.getSettledId());
            ApplyAttachments applyAttachments = applyAttachmentsMapper.selectOne(applyAttachmentsQueryWrapper);
            if(null==applyAttachments){
                throw new Exception("申请附件不存在");
            }
            settleApplyDto.setAttachmentName(applyAttachments.getAttachmentName());
            settleApplyDto.setAttachmentUrl(applyAttachments.getAttachmentUrl());
            settleApplyDto.setServiceName(applyAttachments.getServiceName());
            settleApplyDto.setAttachmentsId(applyAttachments.getAttachmentsId());
            settleApplyDtos.add(settleApplyDto);
        }
        return settleApplyDtos;
    }
}
